package com.ifly.controller;

import com.ifly.entity.User;
import com.ifly.service.UserService;
import com.ifly.utils.ValidateImageCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    //生成验证码
    @GetMapping("code")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        //1.利用工具类拿到验证码
        String securityCode = ValidateImageCodeUtils.getSecurityCode();
        //2.把验证码放入图片
        BufferedImage image = ValidateImageCodeUtils.createImage(securityCode);
        //把验证码存入session作用域中
        session.setAttribute("code",securityCode);
        //响应图片到前端
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"png",outputStream);
    }
    //注册方法
    @PostMapping("register")
    public String register(User user,String code,HttpSession session){
        String  sessioncode = (String) session.getAttribute("code");
        //拿前端输入的验证码与session中的code进行比对
        if (sessioncode.equalsIgnoreCase(code)){
            userService.reqister(user);
            return "redirect:/index";
        }else {
            return "redirect:/toRegist";
        }
    }
    //登陆方法
    @PostMapping("login")
    public String login(String username,String password,HttpSession session){
        User login = userService.login(username, password);
        if (login!=null){
            session.setAttribute("user",login);
            return "redirect:/emp/findall";//跳转到查询所有
        }else {
            return "redirect:/index";//跳转回到登陆页
        }
    }

}
